#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/bio.h>
#include <signal.h>

#define DEFAULT_BUF_SIZE 64

static const int server_port = 4433;

int server_running = 1;

int create_socket(void)
{
    int s;
    int optval = 1;
    struct sockaddr_in addr;

    s = socket(AF_INET, SOCK_STREAM, 0);
    if (s < 0) {
        perror("Unable to create socket");
        exit(EXIT_FAILURE);
    }

    addr.sin_family = AF_INET;
    addr.sin_port = htons(server_port);
    addr.sin_addr.s_addr = INADDR_ANY;

    /* Reuse the address; good for quick restarts */
    if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval))
            < 0) {
        perror("setsockopt(SO_REUSEADDR) failed");
        exit(EXIT_FAILURE);
    }

    if (bind(s, (struct sockaddr*) &addr, sizeof(addr)) < 0) {
        perror("Unable to bind");
        exit(EXIT_FAILURE);
    }

    if (listen(s, 1) < 0) {
        perror("Unable to listen");
        exit(EXIT_FAILURE);
    }

    return s;
}

SSL_CTX* create_context(void)
{
    SSL_CTX *ctx;
    ctx = SSL_CTX_new(TLS_server_method());
    if (ctx == NULL) {
        perror("Unable to create SSL context");
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }

    return ctx;
}

void configure_server_context(SSL_CTX *ctx)
{
    /* Set the key and cert */
    if (SSL_CTX_use_certificate_chain_file(ctx, "cert.pem") <= 0) {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }

    if (SSL_CTX_use_PrivateKey_file(ctx, "key.pem", SSL_FILETYPE_PEM) <= 0) {
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
       if (!SSL_CTX_check_private_key(ctx))
    {
        printf("Private key does not match the certificate public key\n");
        ERR_print_errors_fp(stderr);
        exit(EXIT_FAILURE);
    }
}

void usage()
{
    printf("Usage: sslecho \n");
    exit(EXIT_FAILURE);
}

void print_hex(char *buf, size_t len)
{
    printf("*************************\n");
    for (size_t i = 0; i < len; i++)
        printf("%02X ", (unsigned char)buf[i]);
    printf("\n");
    printf("*************************\n");
}

int main(int argc, char **argv)
{
    SSL_CTX *ssl_ctx = NULL;
    SSL *ssl = NULL;

    int server_skt = -1;
    int client_skt = -1;

    /* used by getline relying on realloc, can't be statically allocated */
    char *txbuf = NULL;
    size_t txcap = 0;

    char rxbuf[128];
    size_t rxcap = sizeof(rxbuf);
    int rxlen;

    struct sockaddr_in addr;
    unsigned int addr_len = sizeof(addr);

    /* ignore SIGPIPE so that server can continue running when client pipe closes abruptly */
    signal(SIGPIPE, SIG_IGN);

    printf("\nsslecho : Simple Echo Server (OpenSSL 3.2.0-dev) : %s : %s\n\n", __DATE__,
            __TIME__);

    if (argc > 1) {
        usage();
    }

    ssl_ctx = create_context();


    printf("We are the server on port: %d\n\n", server_port);

    /* Configure server context with appropriate key files */
    configure_server_context(ssl_ctx);

    /* Create server socket; will bind with server port and listen */
    server_skt = create_socket();
    /*
     * Loop to accept clients.
     * Need to implement timeouts on TCP & SSL connect/read functions
     * before we can catch a CTRL-C and kill the server.
     */
    while (server_running) {
        /* Wait for TCP connection from client */
        client_skt = accept(server_skt, (struct sockaddr*) &addr,
                &addr_len);
        if (client_skt < 0) {
            perror("Unable to accept");
            exit(EXIT_FAILURE);
        }


        printf("Client TCP connection accepted\n");

        /* Create server SSL structure using newly accepted client socket */
        ssl = SSL_new(ssl_ctx);
        SSL_set_fd(ssl, client_skt);

        /* use a different rbio */
        BIO *rbio = BIO_new(BIO_s_mem());
        BIO *wbio = BIO_new(BIO_s_mem());
        char buf[DEFAULT_BUF_SIZE];

        /* Wait for SSL connection from the client */
        if (SSL_accept(ssl) <= 0) {
            ERR_print_errors_fp(stderr);
            server_running = 0;
        } else {

            /* Check for Client authentication error */
            if (SSL_get_verify_result(ssl) != X509_V_OK) {
                printf("SSL Client Authentication error\n");
                exit(EXIT_FAILURE);
            }
            printf("Client SSL connection accepted\n\n");

            SSL_set_bio(ssl, rbio, wbio);

            /* Echo loop */
            while (1) {
                /* Get message from client; will fail if client closes connection */
                ssize_t n = read(client_skt, buf, sizeof(buf));
                // ssize_t ssl_len = 0;
                printf("socket read ret: %ld\n", n);
                if (n > 0) {
                    print_hex(buf, n);
                    // ssl_len
                    BIO_write(rbio, buf, n);
                    rxlen = SSL_read(ssl, rxbuf, rxcap);
                } else {
                    rxlen = -1;
                }

                if (rxlen <= 0) {
                    if (rxlen == 0) {
                        printf("Client closed connection\n");
                    } else {
                        printf("SSL_read returned %d\n", rxlen);
                    }
                    ERR_print_errors_fp(stderr);
                    break;
                }
                /* Insure null terminated input */
                rxbuf[rxlen] = 0;
                /* Look for kill switch */
                if (strcmp(rxbuf, "kill\n") == 0) {
                    /* Terminate...with extreme prejudice */
                    printf("Server received 'kill' command\n");
                    server_running = 0;
                    break;
                }
                /* Show received message */
                printf("Received: %s", rxbuf);
                /* Echo it back */
                if (SSL_write(ssl, rxbuf, rxlen) <= 0) {
                    ERR_print_errors_fp(stderr);
                }

                n = BIO_read(wbio, buf, sizeof(buf));

                write(client_skt, buf, n);
            }
        }
        if (server_running) {
            /* Cleanup for next client */
            SSL_shutdown(ssl);
            SSL_free(ssl);
            close(client_skt);
        }
    }
    printf("Server exiting...\n");
    /* Close up */
    if (ssl != NULL) {
        SSL_shutdown(ssl);
        SSL_free(ssl);
    }
    SSL_CTX_free(ssl_ctx);

    if (server_skt != -1)
        close(server_skt);

    if (txbuf != NULL && txcap > 0)
        free(txbuf);

    printf("sslecho exiting\n");

    return EXIT_SUCCESS;
}
